package com.swfpeep.file
{
	import com.swfpeep.SWFPeep;
	import com.swfpeep.data.SWFFileInfo;
	import com.swfpeep.events.SWFPeepEvent;
	import com.swfpeep.ui.SWFFileListPanel;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	
	import mx.collections.ArrayCollection;

	public class SWFFileManager
	{
		static private var _instance:SWFFileManager;
		
		static public function getInstance(ui:SWFFileListPanel = null):SWFFileManager
		{
			if(_instance == null)
				_instance = new SWFFileManager(ui);
			return _instance;
		}
		
		protected var m_ui:SWFFileListPanel;
		protected var m_file:FileReference;
		protected var m_fileList:ArrayCollection;
		
		public function SWFFileManager(ui:SWFFileListPanel)
		{
			this.m_ui = ui;
			this.initThis();
		}
		
		protected function initThis():void
		{
			m_file = new FileReference;
			m_file.addEventListener(Event.SELECT,onFileSelected);
			m_file.addEventListener(ProgressEvent.PROGRESS,onFileLoadProgress);
			m_file.addEventListener(Event.COMPLETE,onFileLoaded);
			
			m_fileList = new ArrayCollection;
			m_ui.fileList.dataProvider = m_fileList;
			
			m_ui.addFileBtn.addEventListener(MouseEvent.CLICK,onAddFileClick);
			m_ui.parseFileBtn.addEventListener(MouseEvent.CLICK,onParseFileClick);
		}
		
		protected function onAddFileClick(event:MouseEvent):void
		{
			m_file.browse([new FileFilter("SWF格式的文件","*.swf")]);
		}
		
		protected function onFileSelected(event:Event):void
		{
			m_file.load();	
		}
		
		protected function onFileLoadProgress(event:ProgressEvent):void
		{
			SWFPeep.PROGRESS_BAR.setProgress(event.bytesLoaded,event.bytesTotal);
		}
		
		protected function onFileLoaded(event:Event):void
		{
			m_fileList.addItem(new SWFFileInfo(m_file.name,m_file.size / 1024 + " kb",m_file.creationDate.toDateString(),m_file.data));
		}
		
		protected function onParseFileClick(event:MouseEvent):void
		{
			var fireEvent:SWFPeepEvent = new SWFPeepEvent(SWFPeepEvent.ON_PARSE_SWF);
			var swfFileInfo:SWFFileInfo =  m_ui.fileList.selectedItem as SWFFileInfo;
			
			fireEvent.data =swfFileInfo;
			SWFPeep.APP.currentSWFFileInfo = swfFileInfo;
			SWFPeep.APP.dispatchEvent(fireEvent);
		}
	}
}